"use strict";

let debug = require('debug')('district');
let esClient = require('../../model/elasticSearch.js');
let metaInfo = require('../../model/es/district.js');

let __client = esClient.client;
let __index = esClient.index;
let __type = metaInfo.type;
let __thisTypeReady = false;

esClient.createMappingIfNecessary(__type, metaInfo.mapping);

function ElasticDao() {
}
module.exports = new ElasticDao();

let ep = ElasticDao.prototype;
ep.indices = {};

function __checkReady() {
    if (!__thisTypeReady) {
        __thisTypeReady = esClient.readyType.indexOf(__type) >= 0;
    }
    if (!__thisTypeReady) throw new Error('elastic search not ready');
}

ep.create = function*(json) {
    __checkReady();

    debug('elastic create, input', json);
    delete json.__v;

    let result = yield __client.create({
        index: __index,
        type: __type,
        id: json._id.toString(),
        body: json
    });
    debug('elastic create, output', result);
    return result;
};

ep.search = function*(params) {
    __checkReady();

    // quick search
    let q = params.q;
    let result;
    if (q) {
        debug('elastic search, input', q);
        result = yield __client.search({
            index: __index,
            type: __type,
            q: q
        });
    }

    // search by body
    else if (params.body) {
        result = yield __client.search({
            index: __index,
            type: __type,
            analyzer:'ik',
            body: params.body
        });
    }

    // something very complexy
    else {
        let locInfo = params.body;
        let body = {
            query: {
                "filtered": {
                    "query": {"match_all": {}},
                    "filter": {
                        "geo_distance": {
                            "distance": locInfo.radius,
                            "district.loc.coordinates": {
                                "lat": locInfo.lat,
                                "lon": locInfo.lng
                            }
                        }
                    }
                }
            }
        };
        debug('elastic search, input', locInfo);

        result = yield __client.search({
            index: __index,
            type: __type,
            body: body
        });
    }

    debug('elastic search, output', result);
    return result;
};

ep.update = function*(doc) {
    __checkReady();

    let result = yield __client.update({
        index: __index,
        type: __type,
        id: doc._id.toString(),
        body: {doc: doc}
    });

    return result;
};

ep.indices.getMapping = function*() {
    __checkReady();

    debug('elastic indices.getMapping');
    let result = yield __client.indices.getMapping({
        index: __index,
        type: __type
    });
    debug('elastic indices.getMapping output', result);
    return result;
};
